﻿''' <summary>
''' VB code for checking out a book.
''' </summary>
''' <author>AJ Whatling, Feng Jiang, Rick Simpson</author>
Partial Class pages_Common_CheckOutBook
    Inherits System.Web.UI.Page

    ''' <summary>
    ''' Called when the page loads.  Is probably broken.
    ''' </summary>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim CurUserRoles() As String = Roles.GetRolesForUser()
        Dim UsersRole As Integer = 0
        Dim ReqBookIDStr As String = Request.QueryString("bid")
        Dim Op As String = Request.QueryString("op")

        Dim ReservesAllowed As Integer
        Dim CheckoutsAllowed As Integer

        Dim HoldOutTime As Integer ' How long a user can hold a book (6 months for faculty, 3 for students)

        ' Fail if user is not logged in.
        If Not Page.User.Identity.IsAuthenticated Then
            PageUtilities.GenerateError("Must be logged in to check out or reserve book.", OutputOrError)
            Return
        End If

        ' check for invalid book id supplied in url.
        If ReqBookIDStr Is Nothing Then
            PageUtilities.GenerateError("Book not found or invalid book.", OutputOrError)
            Return
        End If

        ' check if op parameter in url exists
        If Op Is Nothing Then
            PageUtilities.GenerateError("Operation must be specified.", OutputOrError)
            LibraryBookDataTier.CloseDown()
            Return
        End If

        ' check for invalid operation parameter in the url
        If Not Op.Equals("c") And Not Op.Equals("r") Then
            PageUtilities.GenerateError("Invalid operation.  Can only checkout or reserve a book.", OutputOrError)
            LibraryBookDataTier.CloseDown()
            Return
        End If

        If LibraryBookDataTier.BookIsUnavailable(ReqBookIDStr) Then
            PageUtilities.GenerateError("Book not available for checking out or reserving.", OutputOrError)
            LibraryBookDataTier.CloseDown()
            Return
        End If

        ' check if the user 
        For Each URole As String In CurUserRoles
            If URole.ToString.ToLower.Equals("librarian") Then
                UsersRole = 1
                Exit For ' Librarian is highest user type, so stop loop if user is librarian.
            ElseIf URole.ToString.ToLower.Equals("student") Then
                UsersRole = 2
                ReservesAllowed = 3
                CheckoutsAllowed = 5
                HoldOutTime = 3
                Exit For ' Student is second highest user type, so stop loop if user is student.
            ElseIf URole.ToString.ToLower.Equals("faculty") Then
                UsersRole = 4
                ReservesAllowed = 5
                CheckoutsAllowed = 10
                HoldOutTime = 6
                Exit For
            Else ' Fail if not in any acceptable role.
                PageUtilities.GenerateError("User is not allowed to reserve or checkout book.", OutputOrError)
                LibraryBookDataTier.CloseDown()
                Return
            End If
        Next

        Dim NumCheckedOut As Integer = LibraryBookDataTier.UserGetNumBooksCheckedOut(Page.User.Identity.Name)
        Dim NumReserved As Integer = LibraryBookDataTier.UserGetNumBooksReserved(Page.User.Identity.Name)

        ' Check if user has exceed maximum allowable check outs/reserves.
        If UsersRole <> 1 Then
            ' Skip "Librarian" role, since they can check out/reserve however many they want.
            Dim HasError As Boolean

            ' Two separate if-statements so that we can show two errors at once.
            ' Makes it a little more informative for the user.
            If NumCheckedOut >= CheckoutsAllowed Then
                PageUtilities.GenerateError("You have checked out maximum number of books you're allowed to check out.", OutputOrError)
                LibraryBookDataTier.CloseDown()
                HasError = True
            End If

            If NumReserved >= ReservesAllowed Then
                PageUtilities.GenerateError("You have reserved the maximum number of books you're allowed to reserve.", OutputOrError)
                LibraryBookDataTier.CloseDown()
                HasError = True
            End If

            If HasError Then
                Return ' Exit the function if there was an error.
            End If
        End If

        ' Add book to ServedBooks table.
        Dim AddBookSQL As String = "INSERT INTO [ServedBooks] ([userID], [bookID], [transactionType], [borrowedDate], [returnDate]) VALUES ('" & Page.User.Identity.Name & "', " & ReqBookIDStr & ", '" & Op & "', '" & Date.Today.ToString & "', '" & (DateAdd(DateInterval.Month, HoldOutTime, Date.Today).ToString) & "')"

        LibraryBookDataTier.ExecuteModify(AddBookSQL)

        ' Update book's record in the Books table to reflect change.
        Dim ChangeBookStatusSQL As String
        If Op.Equals("c") Then
            ChangeBookStatusSQL = "UPDATE [Books] SET [checkOutStatus] = 1, [chekcOutFrequency] = [chekcOutFrequency] + 1 WHERE book_ID = " & ReqBookIDStr
        Else
            ChangeBookStatusSQL = "UPDATE [Books] SET [reserveStatus] = 1, [reserveFrequency] = [reserveFrequency] + 1 WHERE book_ID = " & ReqBookIDStr
        End If

        LibraryBookDataTier.ExecuteModify(ChangeBookStatusSQL)


        LibraryBookDataTier.CloseDown()

        Dim WootMsg As WebControls.Label = New WebControls.Label
        WootMsg.Text = "Book successfully added."
        WootMsg.Attributes.Add("class", "sucess")
        OutputOrError.Controls.Add(WootMsg)

    End Sub
End Class
